Instantiate validators at definition time#2657
Draft
ericproulx wants to merge 4 commits intomasterfrom
Draft
Conversation
Danger ReportNo issues found. |
5d145a5 to
f87920f
Compare
Contributor
Author
|
Missing UPGRADING notes. Working on it |
2ecb403 to
cf04c9d
Compare
Member
|
Is there a tradeoff with things like |
Contributor
Author
e16efcf to
0b9e34b
Compare
a503556 to
2b16ba1
Compare
b744723 to
30b09ea
Compare
246bee6 to
df31408
Compare
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Remove `test-prof` gem from Gemfile - Delete spec/config/spec_test_prof.rb (no-op BeforeAll adapter) - Remove 'config' directory from spec_helper.rb auto-require loop - Replace `let_it_be` with `let` in validator specs Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
734f753 to
f272db7
Compare
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
f272db7 to
f17a1db
Compare
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
f17a1db to
0824af6
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Instantiate validators at definition time and fix thread safety
Summary
Validators are now instantiated at definition time (in
ParamsScopeandContractScope) rather than at request time viaValidatorFactory. This eliminates per-request object allocation overhead and allows expensive setup (option parsing, converter building) to happen once.Because
ParamsScopeinstances are now shared across all concurrent requests, the two instance variables previously mutated at request time (@indexand@params_meeting_dependency) have been moved into a per-requestParamScopeTrackerstored inFiber[], eliminating a long-standing thread-safety race.I18n translation is handled through a shared
Grape::Util::Translationmodule. Validators that need interpolation parameters (e.g.LengthValidator,SameAsValidator) store a Hash{ key: :length, min: 2, max: 5 }as their message.Exceptions::Base#translate_messagedispatches on type — Symbol, Hash, Proc, or String — so translation with the correct locale always happens at error-raise time.Changes
Core architecture
ParamsScope#validateandContractScopenow store validator instances instead of option hashes innamespace_stackable[:validations]ParamsScope#coerce_typereceivesvalidations.extract!(:coerce, :coerce_with, :coerce_message)instead of the full hashEndpoint#run_validatorstakes arequest:keyword arg, reads validators directly frominheritable_setting.route[:saved_validations], and short-circuits withreturn if validators.blank?Endpoint#validationsenumerator methodValidatorFactoryThread safety (
ParamScopeTracker)@indexand@params_meeting_dependencyremoved fromParamsScopeParamScopeTrackerstored inFiber[FIBER_KEY], set/restored around each request inEndpoint#run_validatorsAttributesIterator#store_indiceswrites current + ancestor indices;ParamsScope#full_nameand#qualifying_paramsread from itShared translation module (
Grape::Util::Translation)translate(with fallback locale logic) intoGrape::Util::Translation, included by bothExceptions::BaseandValidators::BaseExceptions::Base#translate_messagenow supports Hash messages:{ key: :symbol, **interpolation_params }for deferred translation with interpolationValidator base (
Validators::Base)fail_fast?is now an explicit public methodvalidate!,message,options_key?to privatehash_like?,option_value,scrub,translate_messagemessageaccepts a block for lazy default generationValidator optimizations — eagerly computed in
initializeAllowBlankValidator: caches@valueand@exception_messageCoerceValidator: resolves type and builds converter at definition time; removestype,converter,valid_type?DefaultValidator: pre-builds@default_calllambdaExceptValuesValidator/ValuesValidator: validates proc arity; pre-builds call lambdaLengthValidator: stores a Hash message for deferred i18n translation with interpolationRegexpValidator/SameAsValidator/PresenceValidator: cache exception messagesAllOrNoneOfValidator,AtLeastOneOfValidator,MutuallyExclusiveValidator,ExactlyOneOfValidator: cache exception messagesContractScopeValidator: no longer inherits fromBase; standalone class with(schema:)constructorparams:argument simplificationGrape::Exceptions::Validation.new(params: [@scope.full_name(attr_name)])simplified toparams: @scope.full_name(attr_name)throughout, sinceValidationnow coerces to array internallySpecs
let_it_be(:app)with per-describelet(:app)blocksLengthValidatorandSameAsValidatorconfirming request-time locale is used regardless of definition-time localeTest plan
bundle exec rspec)